package UILayer;

import java.awt.BorderLayout;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Set;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

import CtrLayer.LeaseCtr;
import ModelLayer.CustomerCollection;

import javax.swing.SwingConstants;

import java.awt.Color;

public class NewLeaseGUI extends JInternalFrame
{
	private JTable machine_table;
	private JComboBox comboBox;
	private LeaseCtr machines;
	private JTextField price_tf;
	private ArrayList<Object[]> selected;
	private HashMap<String, String> names_and_ids;
	private String[] column_names = { "ID", "Machine", "Price"};
	private DateTextField date;
	private JLabel check;
	private String id_cust="";
	private Date set_date= null;
	DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
	
	
	public NewLeaseGUI()
	{
		super("New Lease", true, true, true, true);
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout(0, 0));
		this.addInternalFrameListener(new InternalFrameAdapter()
		{
			public void internalFrameActivated(InternalFrameEvent e)
			{
				refresh();
			}
		});
		machines = new LeaseCtr();
		selected = new ArrayList<>();
		names_and_ids = CustomerCollection.give_names_and_ids();
		
		JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.EAST);
		panel.setLayout(new BorderLayout(200, 100));
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.NORTH);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		check = new JLabel("<html>*You cannot choose<br/>a date before today.</html>");
		check.setForeground(Color.RED);
		check.setHorizontalAlignment(SwingConstants.CENTER);
		panel_1.add(check, BorderLayout.SOUTH);
		check.setVisible(false);
		
		JPanel panel_2 = new JPanel();
		panel_1.add(panel_2, BorderLayout.CENTER);
		
		JLabel lblNewLabel_1 = new JLabel("Return date:");
		panel_2.add(lblNewLabel_1);
		date = new DateTextField();
		panel_2.add(date);
		date.addMouseListener(new MouseAdapter() {
			public void mouseExited(MouseEvent arg0) {
				if (compare_dates()<=0)
				{
					check.setVisible(true);
				}
				else
				{
					check.setVisible(false);
					refresh();
				}
			}
		});
		make_ctr_buttons();
		make_table();
	}

	public NewLeaseGUI (ArrayList<Object[]> i_selected)
	{
		super("New Lease", true, true, true, true);
		selected = i_selected;
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout(0, 0));
		this.addInternalFrameListener(new InternalFrameAdapter()
		{
			public void internalFrameActivated(InternalFrameEvent e)
			{
				refresh();
			}
		});
		machines = new LeaseCtr();
		selected = new ArrayList<>();
		names_and_ids = CustomerCollection.give_names_and_ids();
		JPanel panel_1 = new JPanel();
		getContentPane().add(panel_1, BorderLayout.SOUTH);
		make_ctr_buttons();
		make_table();
	}
	public NewLeaseGUI (ArrayList<Object[]> i_selected,String id_cust, String price, String i_date)
	{
		super("Lease", true, true, true, true);
		this.id_cust=id_cust;
		try
		{
			set_date=(Date) dateFormat.parse(i_date);
		}
		catch (ParseException e) {
		}
		selected = new ArrayList<>();
		selected = i_selected;
		
		HashMap<String, String> temp=new HashMap<>();
		temp.put(CustomerCollection.find_customer(id_cust).get_name(), id_cust);
		names_and_ids = temp;
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout(0, 0));
		machines = new LeaseCtr();
		JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.EAST);
		panel.setLayout(new BorderLayout(200, 100));
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.NORTH);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel_1.add(panel_2, BorderLayout.CENTER);
		
		JLabel lblNewLabel_1 = new JLabel("Return date:");
		panel_2.add(lblNewLabel_1);
		date = new DateTextField();
		panel_2.add(date);
		date.setDate(set_date);
		
		make_ctr_buttons();
		make_table();
		price_tf.setText(price);
		refresh();
	}

	private void make_table()
	{
		final Object[][] filling=null;
		machine_table = new JTable();
		machine_table.setFillsViewportHeight(true);
		machine_table.setModel(new MyTableModel(filling, column_names));
		machine_table.setPreferredScrollableViewportSize(new Dimension(200, 70));
		machine_table.setAutoCreateRowSorter(true);
		machine_table.setRowSelectionAllowed(true);
		machine_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		machine_table.getTableHeader().setReorderingAllowed(false);
		machine_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		JScrollPane scroll_pane = new JScrollPane(machine_table);
		scroll_pane.setBorder(new EmptyBorder(5, 10, 5, 10));
		getContentPane().add(scroll_pane, BorderLayout.CENTER);
	}

	private void refresh()
	{
		double cost = 0;
		Object[][] fill = new Object[selected.size()][3];
		int i = 0;
		for (Object[] data : selected)
		{
			Object[] temp = { data[0], data[1], data[2]};
			fill[i] = temp;
			cost += Double.parseDouble(String.valueOf(data[2]));
			i++;
		}
		machine_table.setModel(new MyTableModel(fill, column_names));
	    DecimalFormat twod = new DecimalFormat("#.00");
	    if (cost>0)
	    {
	    	price_tf.setText(String.valueOf(twod.format(cost*compare_dates())));	
	    }
	    else
	    {
	    	price_tf.setText(String.valueOf(cost));
	    }
	}
	

	private void make_ctr_buttons()
	{
		JPanel ctr_btn_panel = new JPanel();
		ctr_btn_panel.setBorder(new EmptyBorder(3, 3, 0, 3));
		
		getContentPane().add(ctr_btn_panel, BorderLayout.SOUTH);
		GridBagLayout gbl_ctr_btn_panel = new GridBagLayout();
		gbl_ctr_btn_panel.columnWidths = new int[] { 0, 0, 0, 70, 0 };
		gbl_ctr_btn_panel.rowHeights = new int[] { 0, 0 };
		gbl_ctr_btn_panel.columnWeights = new double[] { 1.0, 0.0, 0.0, 0.0,
				Double.MIN_VALUE };
		gbl_ctr_btn_panel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
		ctr_btn_panel.setLayout(gbl_ctr_btn_panel);
		JButton btn_save = new JButton("Create Lease");
		GridBagConstraints gbc_btn_save = new GridBagConstraints();
		gbc_btn_save.anchor = GridBagConstraints.NORTHEAST;
		gbc_btn_save.insets = new Insets(0, 0, 0, 5);
		gbc_btn_save.gridx = 1;
		gbc_btn_save.gridy = 0;
		btn_save.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				create();
			}
		});
		ctr_btn_panel.add(btn_save, gbc_btn_save);

		JButton btn_del = new JButton("Delete Machine");
		GridBagConstraints gbc_btn_del = new GridBagConstraints();
		gbc_btn_del.anchor = GridBagConstraints.WEST;
		gbc_btn_del.gridx = 3;
		gbc_btn_del.gridy = 0;
		btn_del.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				delete();
			}
		});
		
				JButton btn_add = new JButton("Add Machine");
				GridBagConstraints gbc_btn_add = new GridBagConstraints();
				gbc_btn_add.anchor = GridBagConstraints.EAST;
				gbc_btn_add.insets = new Insets(0, 0, 0, 5);
				gbc_btn_add.gridx = 2;
				gbc_btn_add.gridy = 0;
				btn_add.addActionListener(new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
					{
						add();
					}
				});
				ctr_btn_panel.add(btn_add, gbc_btn_add);
		ctr_btn_panel.add(btn_del, gbc_btn_del);
		
		JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.NORTH);
		panel.setLayout(new BorderLayout(0, 0));
		
				JPanel panel_1 = new JPanel();
				panel.add(panel_1, BorderLayout.WEST);
				panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
				JLabel lblNewLabel = new JLabel("Customer");
				panel_1.add(lblNewLabel);
				comboBox = new JComboBox();						
	    panel_1.add(comboBox);
		Set keys = names_and_ids.keySet();
		for(Object key : keys)
		{
			if (key!=null)
			{
				comboBox.addItem(key);
			}
		}							
		
		JPanel panel_2 = new JPanel();
		panel.add(panel_2, BorderLayout.EAST);
		panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		JLabel tot_price_lbl = new JLabel("Estimated total price:");
		panel_2.add(tot_price_lbl,BorderLayout.EAST);

		price_tf = new JTextField();
		price_tf.setEnabled(false);
		panel_2.add(price_tf);
		price_tf.setColumns(10);
		if (!id_cust.equals(""))
		{
			btn_save.setEnabled(false);
			btn_add.setEnabled(false);
			btn_del.setEnabled(false);
		}
		
	}

	private void add()
	{
		AddMachineGUI p = new AddMachineGUI(this);
		getDesktopPane().add(p);
		Point current_win = getLocationOnScreen();
		p.setLocation((int) current_win.getX() + 20, (int) current_win.getY() + 5);
		p.setVisible(true);
		
	}

	private void create()
	{
		if (comboBox.getSelectedIndex() != -1)
		{
			if (!(selected.isEmpty()))
			{
				if (compare_dates()>0)
				{
					
					String name = (String) comboBox.getSelectedItem();
					String id_cust = names_and_ids.get(name);
					ArrayList<String> temp = new ArrayList<>();
					for (int i=0;i<selected.size();i++)
					{
						Object[] x= selected.get(i);
						temp.add(String.valueOf(x[0]));
					}
	                 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	                 sdf.setLenient(false);
	                 String old =sdf.format(date.getDate());
	                 
					String id = machines.create_lease(old, temp,Double.parseDouble(price_tf.getText().replace(',', '.')));
					CustomerCollection.add_lease_to_customer(id_cust, id);
					JOptionPane.showMessageDialog(this, "<html>You successfully created a lease.<br/>ID:"+id+"</html>", "Success", JOptionPane.INFORMATION_MESSAGE);
					dispose();
				}
			}
			else
			{
				JOptionPane.showMessageDialog(this, "You need to add at least one machine to continue.", "Error", JOptionPane.INFORMATION_MESSAGE);
			}
		}
		else
		{
			JOptionPane.showMessageDialog(this, "You need to select a customer.", "Error", JOptionPane.INFORMATION_MESSAGE);
		}
	}

	private void delete()
	{
		int row_index = machine_table.getSelectedRow();
		if (row_index != -1)
		{
			if( machine_table.getModel().getValueAt(row_index, 0) != null)
			{
				for (Object[] data : selected)
				{
					if (data[0].equals(machine_table.getModel().getValueAt(
							row_index, 0)))
					{
						selected.remove(data);
						break;
					}
				}
			}
		}
		refresh();
	}
    private int compare_dates()
    {
		Date temp = date.getDate();
        Date now = new Date();
       double days = (temp.getTime()-now.getTime())/86400000;
        return (int)Math.ceil(days)+1;
    }

	class AddMachineGUI extends JInternalFrame
	{
		private JTextField search_tf;
		private JTable machine_table;
		private NewLeaseGUI instance;

		private String[] column_names = { "Art. number", "Name", "Price"};

		public AddMachineGUI(NewLeaseGUI instance)
		{
			super("Add machine", true, true, true, true);
			this.instance=instance;
			setBounds(100, 100, 300, 350);

			make_search();
			make_ctr_btns();
			make_table();

		}

		private void make_ctr_btns()
		{
			JPanel panel = new JPanel();
			getContentPane().add(panel, BorderLayout.SOUTH);
			panel.setLayout(new BorderLayout(0, 0));

			JButton add_btn = new JButton("Add");
			add_btn.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					add();
				}
			});
			panel.add(add_btn, BorderLayout.WEST);

			JButton cancel_btn = new JButton("Back");
			cancel_btn.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					dispose();
				}
			});
			panel.add(cancel_btn, BorderLayout.EAST);
		}

		private void make_search()
		{
			JPanel panel_1 = new JPanel();
			getContentPane().add(panel_1, BorderLayout.NORTH);
			panel_1.setLayout(new BorderLayout(0, 0));
			JPanel panel_2 = new JPanel();
			panel_1.add(panel_2, BorderLayout.WEST);
			panel_2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

			JLabel search_lbl = new JLabel("Name/ID");
			panel_2.add(search_lbl);

			search_tf = new JTextField();
			panel_2.add(search_tf);
			search_tf.setColumns(10);

			JButton search_btn = new JButton("Search");
			search_btn.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					search();
				}
			});
			panel_2.add(search_btn);
			JButton clear_btn = new JButton("Clear");
			clear_btn.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					search_tf.setText("");
					refresh();
				}
			});
			panel_2.add(clear_btn);
		}

		private void make_table()
		{
			
			final Object[][] filling = machines.display_fine_machines();
			machine_table = new JTable();
			machine_table.setFillsViewportHeight(true);
			machine_table.setModel(new MyTableModel(filling, column_names));
			machine_table.setPreferredScrollableViewportSize(new Dimension(400, 70));
			machine_table.setAutoCreateRowSorter(true);
			machine_table.setRowSelectionAllowed(true);
			machine_table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			machine_table.getTableHeader().setReorderingAllowed(false);
			machine_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			JScrollPane scroll_pane = new JScrollPane(machine_table);
			scroll_pane.setBorder(new EmptyBorder(5, 10, 5, 10));
			getContentPane().add(scroll_pane, BorderLayout.CENTER);
			
		}

		private void add()
		{
			int row_index = machine_table.getSelectedRow();
			boolean added = false;
			if (row_index != -1)
			{
				if( machine_table.getModel().getValueAt(row_index, 0) != null)
				{
					Object[] info = {String.valueOf(machine_table.getModel().getValueAt(row_index, 0)),String.valueOf(machine_table.getModel().getValueAt(row_index, 1)), String.valueOf(machine_table.getModel().getValueAt(row_index, 2))};
					
					for (Object[] position : selected)
					{
						if (position[0].equals(info[0]))
						{
							added = true;
							JOptionPane.showMessageDialog(this, "Couldn't add a machine.\nThis machine is already added.", "Error", JOptionPane.INFORMATION_MESSAGE);
						}
					}
					if (!added)
					{
						selected.add(info);
						instance.refresh();
						JOptionPane.showMessageDialog(this, "You added a machine to the lease.", "Success", JOptionPane.INFORMATION_MESSAGE);
						refresh();
					}
				}
			}
		}

		private void search()
		{
			Object[][] filling = new Object[1][6];
			String info = search_tf.getText();
			
			if (is_numeric(info)&&(machines.is_such_machine_id(info)))
			{
				if ((String.valueOf(machines.display_machine_id(info)[3]).equals("Available"))&&(String.valueOf(machines.display_machine_id(info)[4]).equals("Finished")))
				{
					
					filling[0] = new Object[] {machines.display_machine_id(info)[0],machines.display_machine_id(info)[1],machines.display_machine_id(info)[2]};
				}
			}
			else if ((machines.is_such_machine_name(info))&&(String.valueOf(machines.display_machine_name(info)[3]).equals("Available"))&&(String.valueOf(machines.display_machine_name(info)[4]).equals("Finished")))
			{
				filling[0] = new Object[] {machines.display_machine_name(info)[0],machines.display_machine_name(info)[1],machines.display_machine_name(info)[2]};;
			}
			if (filling[0][0]!=null)
			{
			machine_table.setModel(new MyTableModel(filling, column_names));
			}
			else
			{
				machine_table.setModel(new MyTableModel(new Object[][]{}, column_names));
			}
			}
		
		private void refresh()
		{
			Object[][] filling = machines.display_fine_machines();
			machine_table.setModel(new MyTableModel(filling, column_names));
			
		}

		private boolean is_numeric(String checker)
		{
			try
			{
				int i = Integer.parseInt(checker);
			}
			catch (NumberFormatException nfe)
			{
				return false;
			}
			return true;
		}

	}

}
